﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using SuperX.Common.Helper;

namespace SuperX.Common.Respository
{
    // 
    public class BasicJsonConverter<T> : JsonConverter
    {
        // 
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
        }

        // 
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object result;
            try
            {
                JObject jobject = JObject.Load(reader);
                T t = this.CreateObject(jobject, objectType);
                serializer.Populate(jobject.CreateReader(), t);
                result = t;
            }
            catch
            {
                result = default;
            }
            return result;
        }

        // 
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        // 
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        // 
        public virtual T CreateObject(JObject jObject, Type objectType)
        {
            T t = CreateInstanceUtil.CreateInstance<T>(jObject.GetValue("ClassType", StringComparison.OrdinalIgnoreCase).ToString());
            if (t == null || !t.GetType().IsSubclassOf(objectType))
            {
                return default;
            }
            return t;
        }
    }
}
